﻿using System.Data;
using System.Diagnostics;
using System.Text.RegularExpressions;
using MsgQueueTest.Entity;

namespace MsgQueueTest.Data
{
    public class ContentManager
    {
        public readonly Regex DataRegex = new Regex("<%\\s*([^%>\\s]*)\\s*%>");
        private readonly TemplateManager templateManager;

        public ContentManager()
        {
            templateManager=new TemplateManager();
        }

        public string GetMailBody(Email email)
        {
            var mailTable = GetMailData(email);
            var templateTable = templateManager.GetTemplate(email.TemplateName);
            if(templateTable==null||templateTable.Rows.Count==0)
            {
                return string.Empty;
            }

            var body = templateTable.Rows[0]["Body"].ToString();
            if(string.IsNullOrEmpty(email.Query))
            {
                return body;
            }
            if(mailTable==null||mailTable.Rows.Count==0)
            {
                return body;
            }
            return DataRegex.Replace(body, current => mailTable.Rows[0][current.Groups[1].Value].ToString());
        }

        public  DataTable GetMailData(Email email)
        {
            if(string.IsNullOrEmpty(email.Query))
            {
                return null;
            }
            var query = email.Query.ToLower().Replace("@param1", email.Param1).Replace("@param2", email.Param2);

            return  DataManager.ExecStringCommandDataSet(query);
        }


        public void  SetEmailSended(int notifyId)
        {
            string sql = string.Format("UPDATE DeliveryManager.dbo.notify SET Status='SNT' WHERE NotifyID={0}", notifyId);

            DataManager.ExecStringCommandDataSet(sql);
        }

        public void SetEmailError(int notifyId)
        {
            string sql = string.Format("UPDATE DeliveryManager.dbo.notify SET Status='ERR' WHERE NotifyID={0}", notifyId);

            DataManager.ExecStringCommandDataSet(sql);
        }

        public void Test()
        {
            var s = "There are <%NumSku%> skus ";
            s=DataRegex.Replace(s, "123");
            Debug.Assert("There are 123 skus ".Equals(s));
        }
    }
}
